// 全局变量
var today = new Date();
var todayTxt = today.format('yyyy-MM-dd');
var ultraRecords = [];

var MY_INSTRUMENT_DISINFECT = (function() {

	function loadItem(){
		//清除排序
		var  oTable = document.getElementById("dataTable");
		oTable.sortCol = -1;
		//重置全部排序图标
		$("after").css("opacity",0.3);
		$("before").css("opacity",0.3);

		var params = getParams();
		// 输入有误的情况下，退出
		if (!params){
			return false;
		}
		
		var $tbodySpecimenList = $('#tbodySpecimenList');
		$tbodySpecimenList.empty();
		
		WeKnow.loading();
		
		$.ajax({ 
	        type: "POST", 
	        url: "invs_instrument_disinfect.do/load", 
	        dataType: "json",
	        contentType:"application/json",
	        data: JSON.stringify(params),
	        async: true,//异步调用
	        success: function(data) {
	        	
	        	WeKnow.closeLoading();
	        	
				if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
	        	
	        	if (data.errcode == 0) {
	        		// 把取到的结果放到
	        		var e = '';
	        		
	        		if ( 'datalist' in data && data.datalist.length == 0 ){
	        			WeKnow.errorMsg('没有查询到医疗机构数据');
	        			return;
	        		}
	        		
	        		var businessSubType = $('#businessSubType').val();
	        		
	        		console.log('params.businessSubType==='+params.businessSubType);
	        		
	        		$(data.datalist).each(function( idx,_a){
	        			e+='<tr class="pointer" ';
		        				e+= ' data-institution_id="' + _a.institutionId + '"';
		        				e+= ' data-institution_name="' + _a.institutionName + '"';
	        			e+='>';
        					// 诊所名
	        				e+='<td class="text-left">'+  _a.institutionName + '</td>';
							if ( _a.institutionTypeFirstName ==null ){
								e+='<td class="text-left"><font style="color:red;">未归类</font></td>';
							}else{
								e+='<td class="text-left">'+_a.institutionTypeFirstName + '</td>';
							}
	        				// 状态规则
						    if (params.businessSubType == '101') {
								if ( _a.invsInstrumentSet == 0 ){
									e+='<td class="text-left">不登记</td>';
								} else {
									e+='<td class="text-left">'+  _a.invsInstrumentSet + '天1次</td>';
								}
							} else {
								if ( _a.invsRoomSet == 0 ){
									e+='<td class="text-left">不登记</td>';
								} else {
									e+='<td class="text-left">1天1次</td>';
								}
							}
        					// 登记次数
	        				e+='<td class="text-right">'+_a.registryCnt + '</td>';
	        				// 未处理申诉数 add by zhengxb 2019.11.28 -------------------------
	        				e+='<td class="text-right">'+ (_a.noAppealCnt==null?0:_a.noAppealCnt) + '</td>';
	        				// 登记状态
	        				e+='<td class="text-center">'+ (_a.checkSt==0?'正常': '<font style="color:red;">异常</font>')+'</td>';
        					// 操作
	        				e+='<td class="text-center"><button type="button" name="showDetail" class="btn btn-default btn-sm">查看</button></td>';
	        			e+='</tr>';
	        		});
	        		$tbodySpecimenList.append(e);
	        		
	        	} else if (data.errcode == -1 ) {
	        		WeKnow.errorMsg( data.errMsg );
	        	} else {
	        		WeKnow.systemMsg('查询失败，请重新登录后再试');
	        	}
	        }
		});
	}

	function loadInstitutionUltraviolet() {
		var params = {};
		if ($('#ultraSt').val() !== -1) {
			params.status = $('#ultraSt').val();
		}
		var institutionName = $.trim($('input#institutionNameInput').val());
		if (institutionName.length) {
			params.institutionName = institutionName;
		}
		params.institutionTypeFirst = $('select[name="institutionTypeFirstScreen2"]').val();//医疗机构类别

		var $tbodyUltraIstList = $('#tbodyUltraIstList');
		$tbodyUltraIstList.empty();

		WeKnow.loading();

		$.ajax({
			type: "POST",
			url: "invs_instrument_disinfect.do/ultraviolet/load",
			dataType: "json",
			contentType:"application/json",
			data: JSON.stringify(params),
			async: true,//异步调用
			success: function(data) {

				WeKnow.closeLoading();

				if (!WeKnow.filterAjaxResult(data)) return false; // session过期check

				if (data.errcode === 0) {
					// 把取到的结果放到
					var e = '';

					if ( 'institutionList' in data && data.institutionList.length == 0 ){
						WeKnow.errorMsg('没有查询到医疗机构数据');
						return;
					}
					var bodyHTML = '';
					$(data.institutionList).each((idx, item) => {
						bodyHTML += '<tr><td>' + item.institutionName + '</td><td>'+ (item.institutionTypeFirstName?item.institutionTypeFirstName:"") +'</td><td ' + (item.status === 0 ?  '' : 'style="color: red;"') + '>' + (item.status === 0 ? '正常' : '异常') + '</td>' +
							'<td><button class="ultra-detail" data-ist="' + item.institutionId + '" data-name="' + item.institutionName + '">详情</button></td></tr>';
					});
					if (bodyHTML) {
						$tbodyUltraIstList.append(bodyHTML);

						$tbodyUltraIstList.find('button').on('click', function () {
							var detailParam = {
								institutionId: $(this).data('ist')
							};

							$('#institution_name_sp').text($(this).data('name'));

							$('.input-toggle').hide();
							$('.ultra-toggle').show();

							$.ajax({
								type: "POST",
								url: "invs_instrument_disinfect.do/ultraviolet/load_detail",
								dataType: "json",
								contentType:"application/json",
								data: JSON.stringify(detailParam),
								async: true,//异步调用
								success: function(data) {

									WeKnow.closeLoading();

									if (!WeKnow.filterAjaxResult(data)) return false; // session过期check

									if (data.errcode === 0) {
										console.log(data);
										var $tbodyUI = $('#tbodyUI');
										$tbodyUI.empty();
										if (data.instruments && data.instruments.length) {
											var instrumentsHTML = '';
											$(data.instruments).each((idx, _ins) => {
												var maxHour = Math.floor(_ins.maxTime / 60);
												var useHour = Math.floor(_ins.useTime /60);
												var enableDate = new Date(_ins.enableDate).format('yyyy-MM-dd');
												instrumentsHTML += '<tr><td>' + _ins.name + '</td><td>' + maxHour + '</td>' +
													'<td ' + (_ins.status === 1 ? 'style="color: red"' : '') + '>' + useHour + '</td>' +
													'<td ' + (_ins.status === 1 ? 'style="color: red"' : '') + '>' + (_ins.status === 1 ? '异常' : '正常') + '</td>' +
													'<td>' + enableDate + '</td></tr>';
											});
											$tbodyUI.append(instrumentsHTML);
										}

										if (data.records && data.records.length) {
											ultraRecords = data.records;
											$('#ultraRecordSel').val(-1);
											selectRecords();
										}
									} else if (data.errcode === -1 ) {
										WeKnow.errorMsg( data.errMsg );
									} else {
										WeKnow.systemMsg('查询失败，请重新登录后再试');
									}
								}
							});
						})
					}
				} else if (data.errcode === -1 ) {
					WeKnow.errorMsg( data.errMsg );
				} else {
					WeKnow.systemMsg('查询失败，请重新登录后再试');
				}
			}
		});
	}

	function selectRecords() {
		var selectStatus = $('#ultraRecordSel').val();
		var $tbodyUR = $('#tbodyUR');
		$tbodyUR.empty();
		var recordHTML = '';
		$(ultraRecords).each((idx, _rec) => {
			if (1 * selectStatus === -1 || 1 * selectStatus === _rec.ultraStatus)  {
				var maxHour = Math.floor(_rec.maxTime / 60);
				var useHour = Math.floor(_rec.useTime /60);
				var enableDate = new Date(_rec.createDt).format('yyyy-MM-dd');
				recordHTML += '<tr><td>' + _rec.name + '</td><td>' + _rec.operationDesc + '</td><td>' + maxHour + '</td>' +
					'<td ' + (_rec.ultraStatus === 1 ? 'style="color: red"' : '') + '>' + useHour + '</td>' +
					'<td ' + (_rec.ultraStatus === 1 ? 'style="color: red"' : '') + '>' + (_rec.ultraStatus === 1 ? '异常' : '正常') + '</td>' +
					'<td>' + enableDate + '</td></tr>';
			}
		});
		$tbodyUR.append(recordHTML);
	}

	// 收集页面查询参数
	function getParams(){
		
		var data = getFormComPar();
		
		if (!data){
			return data;
		}
		// 诊所名
		var institutionName = $.trim( $('#institutionName').val());
		if ( institutionName.length ){
			data.institutionName = institutionName;
		}
		data.checkSt = $('#checkSt').val();// 登记状态

		data.institutionTypeFirst = $('select[name="institutionTypeFirstScreen"]').val();//医疗机构类别
		
		return data;
	}
	
	// 收集页面查询参数
	function getDetailParams(institutionId){
		
		var data = getFormComPar();
		
		if (!data){
			return data;
		}
		
		data.institutionId = institutionId;
		return data;
	}
	
	function getFormComPar(){
		
		var data = {};
		
		// 日期 from - to
		var $disinfectDtFrom = $('#disinfectDtFrom');
		if ( !$disinfectDtFrom.val().length ){
			WeKnow.errorMsg('请输入查询开始日期');
			$disinfectDtFrom.focus();
			return false;
		}
		
		var disinfectDtFrom = $disinfectDtFrom.val();
		if ( !MY_VALIDATOR.isDate(disinfectDtFrom,'yyyy-MM-dd')){
			WeKnow.errorMsg('查询开始日期格式不正确');
			$disinfectDtFrom.focus();
			return false;
		}
		data.dtFrom = disinfectDtFrom;
		
		// 查询日期to
		var $disinfectDtTo = $('#disinfectDtTo');
		if ( !$disinfectDtTo.val().length ){
			WeKnow.errorMsg('请输入查询结束日期');
			$disinfectDtTo.focus();
			return false;
		}
		
		var disinfectDtTo = $disinfectDtTo.val();
		if ( !MY_VALIDATOR.isDate(disinfectDtTo,'yyyy-MM-dd')){
			WeKnow.errorMsg('查询结束日期格式不正确');
			$disinfectDtTo.focus();
			return false;
		}
        if($disinfectDtFrom.val()>$disinfectDtTo.val()){
            WeKnow.errorMsg('开始时间不能大于结束时间');
            return false;
        }
		data.dtTo = disinfectDtTo;
		data.businessSubType = $('#businessSubType').val();// 器械 OR 场所
		
		if ( $('#onlyShowAppeal').prop('checked') ){
			data.onlyShowAppeal = 1;//只显示
		}
		
		return data;
	}
	
	return {
		loadItem:loadItem,
		loadInstitutionUltraviolet: loadInstitutionUltraviolet,
		getDetailParams:getDetailParams,
		selectRecords: selectRecords
	}
})();

$(document).ready(function() {
	
	// 页面初期数据查询
	MY_INSTRUMENT_DISINFECT.loadItem();
	
	//查询按钮按下
	$('#search').on('click',function(){
		MY_INSTRUMENT_DISINFECT.loadItem();
	});

	$('#searchUltra').on('click', function () {
		MY_INSTRUMENT_DISINFECT.loadInstitutionUltraviolet();
	});
	
	$('#checkSt').on('change',function(){
		MY_INSTRUMENT_DISINFECT.loadItem();
	});

    $('#ultraSt').on('change',function(){
        MY_INSTRUMENT_DISINFECT.loadInstitutionUltraviolet();
    });
    // 只显示有申诉的机构
	$('#onlyShowAppeal').on('click',function(){
		MY_INSTRUMENT_DISINFECT.loadItem();
	});
	$('select[name="institutionTypeFirstScreen"]').on('change',function(){
		MY_INSTRUMENT_DISINFECT.loadItem();
	});
	$('select[name="institutionTypeFirstScreen2"]').on('change',function(){
		MY_INSTRUMENT_DISINFECT.loadInstitutionUltraviolet();
	});

	
	// 查看明细
	$('#tbodySpecimenList').on('click','button[name="showDetail"]',function(){
		var $that = $(this);
		var institutionId = $that.closest('tr').data('institution_id');
		$('#institutionId').val(institutionId);
		var institution_name  = $that.closest('tr').data('institution_name');
		// 明细模态框显示  当前选中tab
		$('#instrument_modal_title').text($('.active_tab').text());
		// 设置明细页面的诊所名字
		$('#institution_name_dis').text(institution_name);
		// 查询日期显示
		$('#range_dis').text('('+ $('#disinfectDtFrom').val()+'至' + $('#disinfectDtTo').val()+')');
		$('.input-toggle').toggle();//显示部分切换
		// 数据查询
		
		var $tHead  = $('#tHead_SpecimenDetailList');
		var $tbody = $('#tbodySpecimenDetailList');
		var params = MY_INSTRUMENT_DISINFECT.getDetailParams( $('#institutionId').val());
		if(params) {
            MY_INSTRUMENT_DISINFECT_COMMON.loadDetailItem(params, $tHead, $tbody);
        }
	});
	
	// 回主页
	$('#backToWorkspace').on('click',function(){
		MY_INSTRUMENT_DISINFECT.loadItem();//数据刷新
		$('.input-toggle').toggle();//显示部分切换
	});

	// 紫外线页面回主页
	$('#backToUltraMain').on('click', function () {
		$('.ultra-toggle').hide();
		$('#sewage').show();
	});

	$('#ultraRecordSel').on('change', MY_INSTRUMENT_DISINFECT.selectRecords);
	
	// 显示图片
	$('#tbodySpecimenDetailList').on('click','button[name="showImage"]',function(){
		var $that = $(this).closest('tr');
		// 模态框显示诊所名，选定的日期
		$('#imageModalTitle').text($('#institution_name_dis').text() + ' ' + $that.data('serial_date'));
		// 显示试纸图片
		MY_SHOW_IMG.createShowImgModal($that.data('institution_id'),$that.data('paper_img_id'));
	});
	
	// 显示申诉图片
	$('#tbodySpecimenDetailList').on('click','button[name="showAppealAtta"]',function(){
		var $that = $(this);
		var $parentTr = $that.closest('tr');
		
		var appealAtta = $parentTr.data('appeal_atta');
		var institutionId = $('#institutionId').val();
		// 显示交接单图片
		MY_SHOW_IMG.createShowImgModal(institutionId ,appealAtta);
	});
	
	// 处理申诉 OR 取消异常   注：申诉处理由于多个页面共用，故提炼成appeal.js
	$('#tbodySpecimenDetailList').on('click','button[name="closeIllegal"],button[name="check"]',function(){
		var $that = $(this);
		var $parentTr = $that.closest('tr');
		
		var illegalId = $parentTr.data('illegal_id');
//		var selRow = $parentTr.data('sel_row');
		var originBtnName= $that.prop('name');
		
		// 更新用模态框
		var $tHead  = $('#tHead_SpecimenDetailList');
		var $tbody = $('#tbodySpecimenDetailList');
		var params = MY_INSTRUMENT_DISINFECT.getDetailParams( $('#institutionId').val());
		MY_APPEAL.createModalWin
			(illegalId,originBtnName,
				function(){MY_INSTRUMENT_DISINFECT_COMMON.loadDetailItem( params,$tHead,$tbody );}
			);
	});
	
	var ACTIVIE_CLASS = 'active_tab';
	
	// 设备消毒查询 、场所消毒查询
	$('.my_tab').on('click',function(){
		//清除排序
		var  oTable = document.getElementById("dataTable");
		oTable.sortCol = -1;
		//重置全部排序图标
		$("after").css("opacity",0.3);
		$("before").css("opacity",0.3);

		var $that = $(this);
		// 切换tab选中状态
		$('.my_tab').removeClass(ACTIVIE_CLASS);
		$that.addClass(ACTIVIE_CLASS);
		
		var cur_tab = $that.prop('id');
		
		if ( cur_tab == 'disinfect_type' ){
			$('#businessSubType').val('101');
			$('div[name="disinfect"]').show();
			$('div[name="ultraviolet"]').hide();
			MY_INSTRUMENT_DISINFECT.loadItem();
		} else if (cur_tab == 'area_type') {
			$('#businessSubType').val('102');
			$('div[name="disinfect"]').show();
			$('div[name="ultraviolet"]').hide();
			MY_INSTRUMENT_DISINFECT.loadItem();
		} else {
			$('#businessSubType').val('103');
			$('div[name="disinfect"]').hide();
			$('div[name="ultraviolet"]').show();
			MY_INSTRUMENT_DISINFECT.loadInstitutionUltraviolet();
		}

	});
	
	
	$(".my_date_control" ).datepicker({
		changeMonth: true,
		changeYear: true,
        dateFormat: 'yy-mm-dd',//日期格式  
        yearSuffix: '年', //年的后缀
        showMonthAfterYear:true,//是否把月放在年的后面  
        maxDate: (function() {
        	return todayTxt;
        })(),//最大日期  
        yearRange: (function() {
        	// '1990:2010'
        	var year1 = '1900';
        	var year2 = today.getFullYear();
        	return year1 + ':' + year2;
        })(),
        monthNamesShort: ['01','02','03','04','05','06','07','08','09','10','11','12'],
        dayNamesMin: ['日','一','二','三','四','五','六'],
        onUpdatedDatepicker: function(_year, _month, _calendar) {
        	console.log('onUpdatedDatepicker');
        	var $c = $('div#ui-datepicker-div');
			$c.find('td[data-handler="selectDay"]').each(function(idx, d) {
				var $d = $(d);
				$d.css({'pointer-events': 'auto', 'opacity': 1});
    		});
        }
	});
});